package com.glodon.paas.search.parser;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.search.model.RevitStructure;

/**
 * Revit Properties文本解析
 * 
 * @author botao.liao
 * 
 */
@Component("revitTextParser")
public class RevitTextParser implements TextParser {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @SuppressWarnings({ "rawtypes" })
    @Override
    public List<Map> parse(InputStream iStream) {
        List<Map> result = new ArrayList<Map>();
        try {
            List<String> lines = IOUtils.readLines(iStream);
            for (String structure : lines) {
                try {
                    Map line = parseLine(structure);
                    result.add(line);
                } catch (Exception e) {
                    logger.error("failed to parse revit structure: " + structure, e);
                }
            }
        } catch (IOException e) {
            logger.error("failed to read properties.", e);
            throw PaasServerExceptionFactory.systemException("failed to read properties.", e);
        } finally {
            IOUtils.closeQuietly(iStream);
        }
        logger.info("readed {} revit structures", result.size());
        return result;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    private Map parseLine(String line) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(line);
        Map map = new HashMap();
        map.put("id", node.path("Id").asText());
        map.put("name", node.path("Name").asText());
        List<RevitStructure.KeyValue> props = new ArrayList<RevitStructure.KeyValue>();
        Iterator<JsonNode> elements = node.path("Properties").elements();
        while (elements.hasNext()) {// 属性分组
            JsonNode element = elements.next();
            Iterator<String> fieldNames = element.fieldNames();
            while (fieldNames.hasNext()) {
                String key = (String) fieldNames.next().trim();
                String value = element.get(key).textValue().trim();
                RevitStructure.KeyValue keyValue = new RevitStructure.KeyValue(key, value);
                props.add(keyValue);
            }
        }
        map.put("structures", props);
        map.put("content", line);
        return map;
    }
}
